package com.czk.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 工具类
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/2 16:44
 */
public class RabbitmqUtils {
    /**
     * 获取/虚拟机主机Connection
     *
     * @return
     * @throws IOException
     * @throws TimeoutException
     */
    public static Connection getHostConnection() throws IOException, TimeoutException {
        // 创建练级工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        // 创建连接对象
        Connection connection = connectionFactory.newConnection();
        return connection;
    }

    /**
     * 获取/czk虚拟机主机Connection
     *
     * @return
     * @throws IOException
     * @throws TimeoutException
     */
    public static Connection getCzkConnection() throws IOException, TimeoutException {
        // 创建练级工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/czk");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        // 创建连接对象
        Connection connection = connectionFactory.newConnection();
        return connection;
    }

    /**
     * 关闭连接
     *
     * @param channel
     * @param connection
     */
    public static void closeConnection(Channel channel, Connection connection) {
        try {
            if (channel != null && connection != null) {
                channel.close();
                connection.close();
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
